/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    Navigator,
    Platform,
    BackAndroid,
    ToastAndroid,
	NativeModules,
    InteractionManager,
    Animated,
    Modal,
    TouchableWithoutFeedback,
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import Swiper from 'react-native-swiper';
import NavigationBar from '../components/NavigationBar';
import LeftPage from './LeftPage';
import StorageUser from '../lib/plugins/StorageUser';
import shopService from '../lib/services/shopService';
import userService from '../lib/services/userService';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');
export default class root extends Component{
    constructor(props) {
        super(props);
        $this = this;
        this.token = '';
        this.userId = '';
        // 初始状态
        this.state = {
            imgList:[],
            dogLicenseId:'',
            shopName:'',
            shopImage:'',
            shopId:'',
        };
    }

    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getBannerList();
                    $this.getUserDetails();
                });              
            }).catch(err=> {
                console.log(err)
            });
    }
    render(){
        var list = this.state.imgList;
        var len = list.length;
        return (
            <View style={styles.container}>
                <View style={styles.topView}></View>
                <ScrollView>
                    <NavigationBar
                        leftPress={() => {this.showAnimate()}}
                        leftIcon={this.state.shopImage?{uri:this.state.shopImage}:"touxiang"}
                        leftStyle={styles.leftStyle}
                        rightIcon="saomiao"
                        rightStyle={{width:25,height:25, marginRight:15}}
                        titleText={this.state.shopName||'请选择店铺'}
                        rightPress={()=>this.goScanCode()}/>
                    <Swiper autoplay={true}  autoplayTimeout={5} showsButtons={false} width={width} height={300*width/600}>
                        <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                            <ImageWrapper width={width} height={300*width/600} icon={len>0?{uri:list[0].img}:'touxiang'}/>
                        </View>
                        <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                            <ImageWrapper width={width} height={300*width/600} icon={len>0?{uri:list[1].img}:'touxiang'}/>
                        </View>
                        <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                            <ImageWrapper width={width} height={300*width/600} icon={len>0?{uri:list[2].img}:'touxiang'}/>
                        </View>
                    </Swiper>
                    <View style={styles.content}>
                        <Shop
                            onPress={()=>this.jumpTo('ReminPage')}
                            imgKey="yy"
                            name = "预约提醒"/>
                        <Shop
                            onPress={()=>this.jumpTo('Qun')}
                            imgKey="qun"
                            name = "俱乐部"/>
                        <Shop
                            onPress={()=>this.jumpTo('MemberDetails')}
                            imgKey="hyzl"
                            name = "会员资料"/>
                        {/**<Shop
                            onPress={()=>this.jumpTo('ShoppingList')}
                            imgKey="wyjh"
                            name = "我要进货"/>**/}
                        <Shop
                            onPress={()=>this.jumpTo('GoodsManage')}
                            imgKey="spgl"
                            name = "商品管理"/>
                        <Shop
                            onPress={()=>this.jumpTo('ActiveList')}
                            imgKey="fbhd"
                            name = "发布活动"/>
                        <Shop
                            onPress={()=>this.jumpTo('PublicAnimals')}
                            imgKey="htfb"
                            name = "活体发布"/>
                        {/**<Shop
                            onPress={()=>this.jumpTo('AgentCard',this.state.dogLicenseId)}
                            imgKey="dbgz"
                            name = "待办狗证"/>**/}
                    </View>
                </ScrollView>
            </View>
        )
    }
    getUserDetails(){
        var $this = this;
        userService.userDetail(async function(data){
            // alert(JSON.stringify(data))
            if(data.code==10000){
				var user_id = data.data.id+'';
                NativeModules.CommonModule.getRongToken($this.token,user_id,data.data.username,data.data.user_head_img)
                var object = {};
                $this.userId = data.data.id;
                object.userId = data.data.id;
                object.userName = data.data.username;
                await StorageUser._saveUser(object);
            }
        },$this.token);
    }
    showAnimate(){
        // this.props.navigation.navigate('DrawerOpen');
        const {navigate } = this.props.navigation;
        navigate('LeftPage',{upData:(obj)=>{
            this.setState({
                shopName:obj.shopName,
                shopImage:obj.shopImage,
                shopId:obj.shopId,
            })
        }})
    }
    goScanCode(){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('ScanCode',{token:$this.token,userId:$this.userId,actionFun:(data)=>{
            const {navigate } = $this.props.navigation;
            navigate('HistoryList',{dataList:data});
        }})
    }

    jumpTo(page,id){
        var $this = this;
        if((page=='GoodsManage' || page=='ActiveList' || page=='PublicAnimals')&&this.state.shopId==''){
            alert('请先点击左上角头像选择店铺！');
            return;
        }
        const {navigate } = this.props.navigation;
        if(id){
            navigate(page,{token:$this.token,id:id})
        }else{
            navigate(page,{token:$this.token})
        }
        
    }
    getBannerList(){
        var $this = this;
        // if(this.rootData){
        //     var arr = [];
        //     arr[0] = this.rootData['0'];
        //     arr[1] = this.rootData['1'];
        //     arr[2] = this.rootData['2'];
        //     this.setState({
        //         imgList:arr,
        //         dogLicenseId:this.rootData.shop_dog_license_id
        //     })
        // }else{
            shopService.bannerLists(async function(data){
                // alert(JSON.stringify(data));
                if(data.code==10000){
                    // var obj = {};
                    // obj.rootData = data.data;
                    // await StorageUser._saveUser(obj);
                    var arr = [];
                    arr[0] = data.data['0'];
                    arr[1] = data.data['1'];
                    arr[2] = data.data['2'];
                    $this.setState({
                        imgList:arr,
                        dogLicenseId:data.data.shop_dog_license_id
                    })
                }
            },$this.userId,$this.token)
        // }
        
    }
}
class Shop extends Component{
    render(){
        return ( 
            <TouchableOpacity onPress={this.props.onPress}>
                <View style={styles.container1}>
                    <ImageWrapper width={width/16} height={width/16} icon={this.props.imgKey}/>
                    <Text style={{marginTop:10}}>{this.props.name}</Text>
                </View>
            </TouchableOpacity>
        )
    }
}
const styles = StyleSheet.create({
    container:{
        flex:1,
        width:width,
        height:height,
        flexDirection:'column',
        alignItems: 'stretch',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },
        }),

    },
    leftStyle:{
        width:30,
        height:30,
        marginLeft:10,
        ...Platform.select({
            android: {
                borderRadius:60,
            },
            ios: {
                borderRadius:15,
            },
        }),
    },
    content:{
        flexDirection:'row',
        flexWrap:'wrap',

    },
    topView:{
        ...Platform.select({
            ios: {
                height: 20
            },
            android: {
                height:0
            },

        }),
        backgroundColor:'rgb(79,145,237)',

    },
    container1:{
        // flex:1,
        width:width/3,
        height:width/3,
        backgroundColor:'rgb(242,242,242)',
        alignItems:'center',
        justifyContent:'center',
        borderWidth:1,
        borderTopWidth:0,
        borderLeftWidth:0,
        borderColor:"rgba(0,0,0,0.1)"
    },
    img:{
        width:width/16,
        height:width/16
    },
    icon: {
        width: 26,
        height: 26,
    },
    animateStyle:{
        width:7*width/10,
        height:height,
        position:'absolute',
        top:0,
        zIndex:10000,
        paddingBottom:20
    },
    modalBox:{
        flex:1,
        backgroundColor:'rgba(3,3,3,.7)',
        justifyContent:'center',
        alignItems:'center',
    },
});